import Vue from 'vue';
import MyDialog from "@/components/dialog4/MyDialog.vue";
import EventBus from "@/lib/event-bus";

/**
 * 弹框组件的构造器
 * @param ctxCpm
 * @param dlgProps
 * @param onOkClick
 * @param onCancelClick
 * @returns {ExtendedVue<Vue, unknown, unknown, unknown, Record<never, any>, {}, ComponentOptionsMixin, ComponentOptionsMixin>|VNode}
 */
function getDialogConstructor(ctxCpm, dlgProps, onOkClick, onCancelClick) {
	return Vue.extend({
		render(h) {
			return h(
				MyDialog, {
					props: {
						...dlgProps,
						handleOk: onOkClick,
						handleCancel: onCancelClick
					}
				},
				[h(ctxCpm, {
					slot: 'content',
					ref: 'myform',
				},)
				]
			)
		}
	})
}

// 暴露此函数供外部组件调用
/**
 *
 * @param ctxCpm     表单组件
 * @param dlgProps   弹框组件的配置项props
 * @param onOkClick  确认按钮点击事件回调函数
 * @param onCancelClick 取消按钮点击事件回调函数
 * @returns {(function(): void)|*}  弹窗关闭后的回调函数
 */
export const useDialog = (ctxCpm, dlgProps, onOkClick, onCancelClick) => {
	let DialogConstructor = getDialogConstructor(ctxCpm, dlgProps, () => {
		EventBus.$emit('form-submit', {callback: (formData) => {
				onOkClick(formData);
		  }});
	}, onCancelClick);
	const dlg = new DialogConstructor();
	const dlgInstance = dlg.$mount();
	document.body.appendChild(dlgInstance.$el);
	return () => {
		dlgInstance.$el.remove();
		dlgInstance.$destroy();
		EventBus.$off("form-submit");		// 移除表单提交事件监听
	}
}




